package com.zqr.state;

import ch.qos.logback.core.util.TimeUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zqr
 * @since 2022/11/4
 */
// 等会一起测一下sleep(0)是什么状态
public class ThreadStateDemo {
    /**
     * 线程的6种状态
     * new
     * runnable （包括就绪和运行）
     * terminated
     * waiting
     * time_waiting
     * blocked
     *
     * @param args
     */
    public static void main(String[] args) {

        // waiting
        new Thread(() -> {
            while(true) {
                synchronized (ThreadStateDemo.class) {
                    try {
                        ThreadStateDemo.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "waiting-thread").start();

        // time_waiting
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "time_waiting-thread").start();

        // blocked
        new Thread(new BlockedDemo(),"blocked-thread-01").start();
        new Thread(new BlockedDemo(),"blocked-thread-02").start();

        // 测一下sleep(0) -- runnable
        new Thread(() -> {
            while(true){
                try {
                    Thread.sleep(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"sleep(0)-thread").start();
    }

    static class BlockedDemo extends Thread {
        @Override
        public void run() {
            synchronized (BlockedDemo.class) {
                while(true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
